﻿#include "frame.h"

IMPLEMENT_DYNCREATE(GLDoc, CDocument)
IMPLEMENT_DYNCREATE(GLView, CView)
IMPLEMENT_DYNCREATE(GLFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(GLView, CView)
ON_WM_PAINT()
ON_WM_CREATE()
ON_WM_DESTROY()
ON_WM_TIMER()
END_MESSAGE_MAP()

void GLView::OnDraw(CDC *pDC)
{
    if (_glContext)
    {
        // 设置视口大小
        CRect rect;
        GetClientRect(&rect);

        // 绘图上下文
        _glContext->draw(rect.Width(), rect.Height());
    }
}

std::shared_ptr<xi::gl::GL_Context> GLView::CreateContext(int width, int height)
{
    _glContext = std::make_shared<xi::gl::GL_Context>((int)m_hWnd, width, height);
    return _glContext;
}

void GLView::OnPaint()
{
    try
    {
        CPaintDC dc(this); // 创建用于绘制的设备上下文
        OnDraw(&dc);       // 调用 OnDraw 绘制内容
    }
    catch (...)
    {
        std::cerr << "GLView::OnPaint error" << std::endl;
    }
}

int GLView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    if (CView::OnCreate(lpCreateStruct) == -1)
        return -1;

    // 定时器 60 帧
    SetTimer(1, 1000 / 60, NULL);

    return 0;
}

void GLView::OnDestroy()
{
    CView::OnDestroy();

    // 销毁定时器
    KillTimer(1);
}

void GLView::OnTimer(UINT_PTR nIDEvent)
{
    // 触发刷新
    ::InvalidateRect(this->m_hWnd, NULL, FALSE);

    CView::OnTimer(nIDEvent);
}
